<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/16
 * Time: 15:03
 */

namespace App\CronTask;


use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\HttpClient\HttpClient;

class CompositeStatsCron extends AbstractCronTask
{
    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        //return '@daily';
        return '*/1 * * * *';
    }

    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        // 定时任务名称
        return 'composite_stats';
    }

    static function run(\swoole_server $server, int $taskId, int $fromWorkerId, $flags = null)
    {
        $team_ids = MysqlPool::invoke(function (MysqlObject $db){
            return $db->getColumn('siam_lolteams','team_id');
        });

        foreach ($team_ids as $team_id){
            $url = UrlEnums::FJURL.UrlEnums::LOL_COMPOSITE_STAS.'?version=2&team_id='.$team_id;
            $client = new HttpClient($url);
            list($s1, $s2) = explode(' ', microtime());
            $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
            $option = [
                'path'      => UrlEnums::LOL_COMPOSITE_STAS,
                'api_time'  => $microtime
            ];
            $header = Auth::getInstance()->header($option);
            $client->setHeaders($header,true,false);
            $response = $client->get();
            $data = $response->getBody();
            $data = json_decode($data,true);
            MysqlPool::invoke(function (MysqlObject $db)use($team_id,$data){
                if( isset($data['code']) && $data['code'] == 200 && $data['data'] ){
                    $res = $db->where('team_id',$team_id)->update('siam_lolteams',[
                        'score' => $data['data']['score']
                    ]);
                }
            });

        }
    }
}